import axios from 'axios'
import { message as Message } from 'ant-design-vue'
import app from '@/main.js'
import router from '@/router'
import { useAccountStore } from '@/stores/account'
import { storeToRefs } from 'pinia'
let request = axios.create({
  baseURL: !APP_MOCK_ENABLE ? import.meta.env.VITE_APP_API_BASE : '',
  timeout: 20000,
})

request.interceptors.request.use(
  config => {
    app?.config?.globalProperties?.$progressBar?.start()
    /**
     * 用户信息
     */
    let accountStore = useAccountStore()
    let account = storeToRefs(accountStore)
    config.headers['Authorization'] = 'Bearer ' + account.token.value
    // if (!config.headers['authorization']) {
    //   config.headers['authorization'] = account.token.value
    // }
    // if (!config.headers['x-rbac-token']) {
    //   if (authorization) {
    //     let regToken = new RegExp(`^V1#${APP_ID}#`)
    //     let token = authorization.replace(regToken, '')
    //     config.headers['x-rbac-token'] = token
    //   }
    // }
    return config
  },
  error => {
    app?.config?.globalProperties?.$progressBar?.end()
    return Promise.reject(error)
  },
)

request.interceptors.response.use(
  response => {
    app?.config?.globalProperties?.$progressBar?.end()
    let contentType = response.headers['content-type']
    // 如果不是json则直接返回data
    if (
      (contentType && !contentType.includes('json')) ||
      response.config.customInterceptorsResponse === true
    ) {
      return response
    }
    let result = response.data
    if (!result?.success) {
      if (response?.config?.customMessageError !== true) {
        Message.error(result?.errorMessage)
      }
      if (result.errorCode == 401) {
        let accountStore = useAccountStore()
        accountStore.logout()
        router.push('/sign/login')
      }
      return Promise.reject(result)
    }
    return result
  },
  async error => {
    app?.config?.globalProperties?.$progressBar?.end()
    let result = error?.response?.data
    if (error?.config?.customMessageError !== true) {
      let message = result?.message || error?.message || 'error'
      Message.error(message)
    }
    if (error.status === 401) {
      let accountStore = useAccountStore()
      accountStore.logout()
      router.push('/sign/login')
    }
    return Promise.reject(error)
  },
)

export default request
